const { defineConfig } = require("@vue/cli-service");
const os = require("os");

const cp = require("child_process");

// // exec
// cp.exec('node ./dir/test1.js', (err, stdout, stderr) => {
//   console.log(stdout);
// });
// // execFile
// cp.execFile('node', ['./dir/test1.js'],(err, stdout, stderr) => {
//   console.log(stdout);
// });
// // fork
// cp.fork('./dir/test1.js',
//   { silent: false }
// );

const getLocalIP = () => {
    const interfaces = os.networkInterfaces();
    for (const devName in interfaces) {
        const iface = interfaces[devName];
        for (let i = 0; i < iface.length; i++) {
            const alias = iface[i];
            if (
                alias.family === "IPv4" &&
                alias.address !== "127.0.0.1" &&
                !alias.internal
            ) {
                return alias.address;
            }
        }
    }
    return null;
};

class ElectronRun {
    constructor(ctx, doneCallback, emitCallback) {
        this.emitCallback = emitCallback;
        this.doneCallback = doneCallback;
    }
    apply(compiler) {
        compiler.hooks.done.tap("help", () => {
            console.log(this);
            if (!this.run) {
                process.env.ELECTRON_URL = getLocalIP() + ":" + process.finderPort;
                const cpw = cp.spawn("npm run electron", {
                    shell: true,
                    detached: false,
                    //stdio: "pipe",
                    stdout: "ignore",
                });
                cpw.stdout.pipe(process.stdout);
                cpw.stderr.pipe(process.stdout);
                cpw.stdin.pipe(process.stdout);
                console.log(process.env.PORT);

                // cpw.stderr.on("data", function(data) {
                //     //Here is where the error output goes

                //     console.log("stderr: " + data);
                // });
                // cpw.stdout.on("data", (msg) => {
                //     console.log(msg.toString());
                // });
                this.run = true;
                cpw.on("exit", () => {
                    this.run = false;
                });
                process.on("exit", () => {
                    cpw.kill();
                });
            }
        });
    }
}
module.exports = defineConfig({
    transpileDependencies: true,
    chainWebpack(config) {},
    configureWebpack: {
        plugins: [new ElectronRun()],
    },
});